<?php

namespace app\controller;

use app\BaseController;
use app\model\DarenSwBind;
use app\model\DyUser;
use app\model\DyUserAddress;
use app\model\UserInfo;
use app\model\Wiseman;
use app\traits\CommonTrait;
use app\traits\TemplateMsgTrait;
use Endroid\QrCode\QrCode;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use Hashids\Hashids;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use app\validate\DyUserAddress as AddressCheck;
use app\model\User;

class DyAuth extends BaseController
{
    use CommonTrait;
    use TemplateMsgTrait;

    //生成抖音授权二维码
    public function dyAuthCode()
    {
        $uid = getUid();
        $base64 = Request::get('base64', 0);
        $hashIds = new Hashids();
        $hashUserId = $hashIds->encode($uid);
        $baseUrl = 'https://open.douyin.com/platform/oauth/connect';
        $param = [
            'state' => $hashUserId,
            'client_key' => config('douyin.client_key'),
            'response_type' => 'code',
            'scope' => 'user_info,mobile_alert',
            'redirect_uri' => config('douyin.redirect_url')
        ];
        $authUrl = $baseUrl . '?' . http_build_query($param);
        $qrCode = new QrCode($authUrl);
        $stream = $qrCode->writeString();
        if ($base64 == 0) {
            //返回图片
            return response($stream, 200, ['Content-Type' => 'image/png']);
        } else {
            //返回base64url
            $base64Url = 'data:image/png;base64,' . base64_encode($qrCode->writeString());
            return $this->apiJson(1, 'success', ['base64_url' => $base64Url]);
        }
    }

    //授权回调
    public function dyAuthCallback()
    {
        $bindSuccessUrl = 'https://api.douwuku.com/bound_result?err_code=0';
        $bindFailUrl = 'https://api.douwuku.com/bound_result?err_code=1';
        $unBindUrl = 'https://api.douwuku.com/bound_result?err_code=2';
        $code = Request::get('code');
        $state = Request::get('state');
        if (!$code || !$state) {
            return redirect($bindFailUrl);
        }
        $payload = [
            'client_key' => config('douyin.client_key'),
            'client_secret' => config('douyin.client_secret'),
            'code' => Request::get('code'),
            'grant_type' => 'authorization_code'
        ];
        $accessTokenUrl = 'https://open.douyin.com/oauth/access_token';
        try {
            $client = new Client();
            $accessTokenResponse = $client->request('GET', $accessTokenUrl, ['query' => $payload, 'timeout' => 5]);
        } catch (\Exception $e) {
            Log::info('获取access_token失败,' . $e->getMessage());
            return redirect($bindFailUrl);
        }
        $accessResult = json_decode($accessTokenResponse->getBody()->getContents(), true);
        if ($accessResult['data']['error_code'] == 0) {
            $userInfoUrl = 'https://open.douyin.com/oauth/userinfo/';
            $payload = [
                'access_token' => $accessResult['data']['access_token'],
                'open_id' => $accessResult['data']['open_id']
            ];
            try {
                $userInfoResponse = $client->request('GET', $userInfoUrl, ['query' => $payload, 'timeout' => 5]);
            } catch (\Exception $e) {
                Log::info('获取用户信息失败,' . $e->getMessage());
                return redirect($bindFailUrl);
            }
            $userInfoResult = json_decode($userInfoResponse->getBody()->getContents(), true);
            if ($userInfoResult['data']['error_code'] == 0) {
                Log::info($userInfoResult['data']);
                $hashUid = $state;
                try {
                    $hashIds = new Hashids();
                    $userIds = $hashIds->decode($hashUid);
                    $uid = $userIds[0];
                } catch (\Exception $e) {
                    Log::info('授权解密uid失败' . $e->getMessage());
                    return redirect($bindFailUrl);
                }
                $encryptMobile = isset($userInfoResult['data']['encrypt_mobile'])?$userInfoResult['data']['encrypt_mobile']:'';
                if($encryptMobile){
                    $iv = substr(config('douyin.client_secret'), 0, 16);
                    $phone = openssl_decrypt($encryptMobile, 'aes-256-cbc', config('douyin.client_secret'), 0, $iv);
                }else{
                    $phone = '';
                }
                $dyUser = DyUser::where(['open_id' => $userInfoResult['data']['open_id']])->field('user_id,dy_name,dy_id')->findOrEmpty();
                if ($dyUser->isEmpty()) {
                    $userInfo = [
                        'user_id' => $uid,
                        'open_id' => $userInfoResult['data']['open_id'],
                        'union_id' => $userInfoResult['data']['union_id'],
                        'dy_id' => '',
                        'dy_name' => $userInfoResult['data']['nickname'],
                        'dy_intro' => '',
                        'avatar' => $userInfoResult['data']['avatar'],
                        'access_token' => $accessResult['data']['access_token'],
                        'expires_in' => time() + $accessResult['data']['expires_in'],
                        'gender'=>$userInfoResult['data']['gender'],
                        'country'=>$userInfoResult['data']['country']?$userInfoResult['data']['country']:'其他',
                        'province'=>$userInfoResult['data']['province']?$userInfoResult['data']['province']:'其他',
                        'city'=>$userInfoResult['data']['city']?$userInfoResult['data']['city']:'其他',
                        'phone'=>$phone
                    ];
                    DyUser::create($userInfo);
                } else {
                    $userInfo = [
                        'phone'=>$phone,
                        'is_del' => 0,
                        'dy_name' => $userInfoResult['data']['nickname'],
                        'avatar' => $userInfoResult['data']['avatar'],
                        'gender'=>$userInfoResult['data']['gender'],
                        'country'=>$userInfoResult['data']['country']?$userInfoResult['data']['country']:'其他',
                        'province'=>$userInfoResult['data']['province']?$userInfoResult['data']['province']:'其他',
                        'city'=>$userInfoResult['data']['city']?$userInfoResult['data']['city']:'其他',
                        'access_token' => $accessResult['data']['access_token'],
                        'expires_in' => time() + $accessResult['data']['expires_in']
                    ];
                    if($uid == $dyUser['user_id']){
                        DyUser::where(['open_id' => $userInfoResult['data']['open_id']])->update($userInfo);
                    }else{
                        $name = User::where(['id'=>$dyUser['user_id']])->field('wx_nickname,name')->find();
                        $openId = UserInfo::where(['user_id'=>$dyUser['user_id']])->value('openid');
                        if(!$name['wx_nickname']){
                            $name = $name['name'];
                        }else{
                            $name = $name['wx_nickname'];
                        }
                        $unBindUrl = $unBindUrl.'&name='.$name;
                        $userInfo['user_id'] = $uid;
                        $userInfo['is_auth'] = 0;
                        DyUser::where(['open_id' => $userInfoResult['data']['open_id']])->update($userInfo);
                        if($openId){
                            $pagePath = 'pakeageDaren/pages/accountList/index';
                            $data = [
                                "first" => [
                                    "value" => "你好,你之前绑定的抖音账号已被解除"
                                ],
                                "keyword1" => [
                                    "value" => $dyUser['dy_name']
                                ],
                                "keyword2" => [
                                    "value" => date('Y-m-d H:i', time())
                                ],
                                "remark" => [
                                    "value" => "若有需要,请重新绑定"
                                ],
                            ];
                            $result = $this->uniformMessageSend($openId, config('app.template.unbind'), $data, $pagePath);
                            if($result['code']!=1){
                                Log::info('推送解绑公众号消息失败');
                                Log::info($result);
                            }
                        }
                        return redirect($unBindUrl);
                    }
                }
                return redirect($bindSuccessUrl);
            } else {
                Log::info('获取用户信息失败' . $userInfoResult['data']['description']);
                return redirect($bindFailUrl);
            }
        } else {
            Log::info('获取access_token失败' . $accessResult['data']['description']);
            return redirect($bindFailUrl);
        }
    }

    //抖音绑定结果
    public function boundResult()
    {
        $errCode = Request::get('err_code', 0);
        $name = Request::get('name', '');
        switch ($errCode){
            case 0:
                $msg = '认证成功';
                break;
            case 2:
                $msg = '绑定成功,"'.$name.'"下的抖音账号已解绑';
                break;
            default:
                $msg = '绑定失败,请更换一个抖音号重试';
                break;
        }
        return view('bound_result', ['msg' => $msg]);
    }

    //生成抖音创作服务平台二维码
    public function creatorCode()
    {
        $uid = getUid();
        $dyId = Request::get('dy_id', 0);
        $base64 = Request::get('base64', 1);
        if (!$dyId) {
            return $this->apiJson(-1, '缺少参数');
        }
        $dyUserExist = DyUser::where(['id'=>$dyId,'user_id'=>$uid,'is_del'=>0])->findOrEmpty();
        if($dyUserExist->isEmpty()){
            return $this->apiJson(-1,'参数错误');
        }
        $payload = [
            'next' => 'https://creator.douyin.com/creator-micro/home',
            'aid' => 2906,
            'is_vcd' => 1,
            'fp' => 'kp28rvnr_hFlOqrRN_69Sr_45Kv_9IEk_JGQcIevDzyKK',
            'service' => 'https://creator.douyin.com'
        ];
        $accessTokenUrl = 'https://sso.douyin.com/get_qrcode/';
        $referUrl = "https://creator.douyin.com/";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        try {
            $client = new Client();
            $response = $client->request('GET', $accessTokenUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        //获取二维码地址 qrcode_index_url
        $result = json_decode($response->getBody()->getContents(), true);
        if ($result['error_code'] == 0) {
            //token 绑定信息
            $cacheData = [
                'dy_id' => $dyId,
                'uid' => $uid
            ];
            Cache::store('file')->set($result['data']['token'], $cacheData, 300);
            $qrCodeIndexUrl = $result['data']['qrcode_index_url'];
            if ($base64 == 0) {
                Log::info('token:' . $result['data']['token']);
                // 返回图片
                $qrCode = new QrCode($qrCodeIndexUrl);
                $stream = $qrCode->writeString();
                return response($stream, 200, ['Content-Type' => 'image/png']);
            } else {
                // 返回base64url
                $base64Url = 'data:image/png;base64,' . $result['data']['qrcode'];
                return $this->apiJson(1, 'success', ['base64_url' => $base64Url, 'token' => $result['data']['token']]);
            }
        } else {
            return $this->apiJson(-1, $result['description'], $result);
        }
    }

    //检测抖音创作服务平台 二维码是否过期
    public function checkQrStatus()
    {
        $uid = getUid();
        $token = Request::post('token');
        $tokenUrl = 'https://sso.douyin.com/check_qrconnect/';
        $payload = [
            'next' => 'https://creator.douyin.com/creator-micro/home',
            'token' => $token,
            'service' => 'https://creator.douyin.com/?logintype=user&loginapp=douyin&jump=https://creator.douyin.com/creator-micro/home',
            'correct_service' => 'https://creator.douyin.com/?logintype=user&loginapp=douyin&jump=https://creator.douyin.com/creator-micro/home',
            'aid' => 2906,
            'is_vcd' => 1,
            'fp' => 'kp28rvnr_hFlOqrRN_69Sr_45Kv_9IEk_JGQcIevDzyKK'
        ];
        $referUrl = "https://creator.douyin.com/";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        try {
            $client = new Client();
            $response = $client->request('GET', $tokenUrl, ['query' => $payload, 'headers' => $headers, 'timeout' => 5]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if ($result['error_code'] == 0) {
            $status = $result['data']['status'];
            $redirectUrl = '';
            switch ($status) {
                case '1':
                    $msg = '二维码未失效，请扫码！';
                    break;
                case '2':
                    $msg = '已扫码，请确认';
                    break;
                case '3':
                    $msg = '已确认，登录成功！';
                    $redirectUrl = $result['data']['redirect_url'];
                    break;
                case '5':
                default:
                    $status = '5';
                    $msg = '二维码已失效';
                    break;
            }
            $status = intval($status);
            if ($redirectUrl) {
                $cacheData = Cache::store('file')->get($token);
                $loginCookie = $response->getHeader('Set-Cookie');
                $cookieArr = [];
                foreach ($loginCookie as $val) {
                    $newSub = explode('=', substr($val, 0, strpos($val, ';')));
                    $cookieArr[$newSub[0]] = $newSub[1];
                }
                //获取回调cookie
                $cookie = $this->callback($redirectUrl, $loginCookie);
                $redirectCookieArr = [];
                foreach ($cookie as $r) {
                    $redirectSub = explode('=', substr($r, 0, strpos($r, ';')));
                    $redirectCookieArr[$redirectSub[0]] = $redirectSub[1];
                }
                //获取用户信息
                $redirectCookieJar = CookieJar::fromArray($redirectCookieArr, 'creator.douyin.com');
                $url = 'https://creator.douyin.com/web/api/media/user/info/';
                $referUrl = "https://creator.douyin.com/creator-micro/home";
                $headers = [
                    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
                    'Referer' => $referUrl
                ];
                $payload = [
                    '_signature' => '_02B4Z6wo00d017.vTVQAAIDADx6hnrpev8O.60nAAI9gvw3K64mC-2CysY0sc9olgcs8ktqctlodAx-jORrDnTpXrIo5Xo4JP0PgBpnsU5qqGg2kcpPKgK6oitG3QEUEb342N1dEV3r4l-5t3e'
                ];
                try {
                    $client = new Client();
                    $response = $client->request('GET', $url, ['query' => $payload, 'headers' => $headers, 'cookies' => $redirectCookieJar, 'timeout' => 5]);
                } catch (\Exception $e) {
                    return $this->apiJson(-1, $e->getMessage());
                }
                $result = json_decode($response->getBody()->getContents(), true);
                Log::info($result);
                if ($result['status_code'] == 0) {
                    if($cacheData){
                        $dyUser = DyUser::where(['user_id'=>$cacheData['uid'],'id'=>$cacheData['dy_id']])->find();
                        if(!$dyUser||$cacheData['uid'] != $uid){
                            return $this->apiJson(-1, '参数错误');
                        }
                        DyUser::where(['open_id'=>$dyUser['open_id']])
                            ->update([
                                'dy_id'=>$result['user']['unique_id']?$result['user']['unique_id']:$result['user']['short_id'],
                                'dy_uid'=>$result['user']['uid'],
                                'works'=>$result['user']['aweme_count'],
                                'likes'=>$result['user']['total_favorited'],
                                'fans'=>$result['user']['follower_count'],
                                'follows'=>$result['user']['following_count'],
                                'dy_intro'=>$result['user']['signature'],
                                'is_auth'=>1
                            ]);
                        $wiseManExist = Wiseman::where(['author_id'=>$result['user']['uid']])->field('id')->findOrEmpty();
                        //检测是否有绑定商务,没绑定的就用系统默认的商务
                        $swUserId = DarenSwBind::where(['dr_user_id' => $uid])->value('sw_user_id');
                        if (!$swUserId) {
                            $swUserId = 1;
                        }
                        if($wiseManExist->isEmpty()){
                            Wiseman::create([
                                'user_id'=>$swUserId,
                                'sec_uid'=>$result['user']['sec_uid'],
                                'nickname'=>$dyUser['dy_name'],
                                'avatar'=>$dyUser['avatar'],
                                'dy_id'=>$result['user']['unique_id']?$result['user']['unique_id']:$result['user']['short_id'],
                                'author_id'=>$result['user']['uid'],
                                'introduction'=>$result['user']['signature'],
                                'fans_num'=>$result['user']['follower_count'],
                                'link_num'=>$result['user']['total_favorited'],
                                'works_num'=>$result['user']['aweme_count'],
                                'gender'=>$dyUser['gender'],
                                'city'=>$dyUser['province'].'.'.$dyUser['city'],
                                'phone'=>$dyUser['phone'],
                                'introduction'=>$dyUser['dy_intro']
                            ]);
                        }else{
                            Wiseman::where(['author_id'=>$result['user']['uid']])->update([
                                'user_id'=>$swUserId,
                                'sec_uid'=>$result['user']['sec_uid'],
                                'nickname'=>$dyUser['dy_name'],
                                'avatar'=>$dyUser['avatar'],
                                'dy_id'=>$result['user']['unique_id']?$result['user']['unique_id']:$result['user']['short_id'],
                                'author_id'=>$result['user']['uid'],
                                'introduction'=>$result['user']['signature'],
                                'fans_num'=>$result['user']['follower_count'],
                                'link_num'=>$result['user']['total_favorited'],
                                'works_num'=>$result['user']['aweme_count'],
                                'gender'=>$dyUser['gender'],
                                'city'=>$dyUser['province'].'.'.$dyUser['city'],
                                'phone'=>$dyUser['phone'],
                                'introduction'=>$dyUser['dy_intro']
                            ]);
                        }
                    }
                    return $this->apiJson(3, 'success', $result);
                } else {
                   // Log::info('Cookies值已经失效，请重新扫码登录');
                    return $this->apiJson(5, '二维码已失效', $result);
                }
            }
            return $this->apiJson($status, $msg, $result);
        } else {
            return $this->apiJson(-1, $result['description'], $result);
        }
    }

    //重定向
    public function callback($redirectUrl, $cookie)
    {
        $referUrl = "https://creator.douyin.com/creator-micro/home";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $cookieArr = [];
        foreach ($cookie as $val) {
            $newSub = explode('=', substr($val, 0, strpos($val, ';')));
            $cookieArr[$newSub[0]] = $newSub[1];
        }
        try {
            $cookieJar = CookieJar::fromArray($cookieArr, 'creator.douyin.com');
            $client = new Client();
            $response = $client->request('GET', $redirectUrl, ['headers' => $headers, 'allow_redirects' => false, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            return '';
        }
        if ($response->getStatusCode() === 302) {
            $redirect = $response->getHeaderLine('Location');
            $cookie = $response->getHeader('Set-Cookie') ?? $cookie;
            $cookie = $this->callback($redirect, $cookie);
        }
        $cookie = $response->getHeader('Set-Cookie') ?? $cookie;
        Log::info(json_decode($response->getBody()->getContents(), true));
        return $cookie;
    }

    //抖音用户信息
    public function dyUserInfo()
    {
        $url = 'https://creator.douyin.com/web/api/media/user/info/';
        $referUrl = "https://creator.douyin.com/creator-micro/home";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl
        ];
        $cookies = [
            'passport_csrf_token_default' => '975acd72b8ae2e9d21f8da24e0345ed6',
            'passport_csrf_token' => '975acd72b8ae2e9d21f8da24e0345ed6',
            'n_mh' => 'q_Lw8p8dwgb91irwavm19tur3kRgafNXpsGC-eMrOnY',
            'ttcid' => '4d5646fb9bab4f7baa0226c5b950d06512',
            'csrf_token' => 'YQbgCoTsxDKScjVafAniNcubaRKHnBDk',
            'MONITOR_WEB_ID' => 'fe401dbb-e76e-455f-870a-cdd602bd5468',
            'sso_auth_status' => '933d1f9faade2b980d745f313fba267d',
            'sso_auth_status_ss' => '933d1f9faade2b980d745f313fba267d',
            'd_ticket' => '6b527e5d62704e59d7ecd4ce7d5c4b95c70b1',
            'oc_login_type' => 'LOGIN_PERSON',
            'csrf_session_id' => '97242e63829d405a9c9fd9274a1114fb',
            's_v_web_id' => 'kp3bdped_6B5D3Eso_LPKA_4uds_97z4_6QvtmoSiN6rA',
            'sso_uid_tt' => 'a60f521cf3c0ce9bcab8ec6f864fbf2e',
            'sso_uid_tt_ss' => 'a60f521cf3c0ce9bcab8ec6f864fbf2e',
            'toutiao_sso_user' => 'b4ddc411c42977dc89c9f73bd4cc5a94',
            'toutiao_sso_user_ss' => 'b4ddc411c42977dc89c9f73bd4cc5a94',
            'odin_tt' => 'f523547139e971f8003a2800400e7e969a56e19133e2330d416a16cf6f5d8d7dc4ea95e819267489baa18eb5fd815ea0',
            'passport_auth_status_ss' => '13d286044e3589e867f552d0d1ed483e%2Cc8b4795ad47fb0f3e02fe84267d5a825',
            'sid_guard' => 'f28bdadaeefb3982d694608b2f194cb0%7C1621904948%7C5184000%7CSat%2C+24-Jul-2021+01%3A09%3A08+GMT',
            'uid_tt' => '17b02c3599bd11bda7a824651f717202',
            'uid_tt_ss' => '17b02c3599bd11bda7a824651f717202',
            //该值有效
            'sid_tt' => 'f28bdadaeefb3982d694608b2f194cb0',
            'sessionid' => 'f28bdadaeefb3982d694608b2f194cb0',
            'sessionid_ss' => 'f28bdadaeefb3982d694608b2f194cb0',
            'passport_auth_status' => '13d286044e3589e867f552d0d1ed483e%2Cc8b4795ad47fb0f3e02fe84267d5a825',
            'tt_scid' => 'Z.U8XKQo6ezVjbYKD8HDoRF71o7OnpQak2ZiBBGG9msja4nFyvU3V.QfH9LSepIL55c0',
            'ttwid' => '1%7CcVjrx66juUIYAgMwRQmtUUEBo_wQJgasSsPK7lbI6ZE%7C1621905370%7C3f3d885649316a91bdf5d3b7f02758021acfa94d10a0476e580c706b63ddedd9',
        ];
        $payload = [
            '_signature' => '_02B4Z6wo00d017.vTVQAAIDADx6hnrpev8O.60nAAI9gvw3K64mC-2CysY0sc9olgcs8ktqctlodAx-jORrDnTpXrIo5Xo4JP0PgBpnsU5qqGg2kcpPKgK6oitG3QEUEb342N1dEV3r4l-5t3e'
        ];
        $cookieJar = CookieJar::fromArray($cookies, 'creator.douyin.com');
        try {
            $client = new Client();
            $response = $client->request('GET', $url, ['query' => $payload, 'headers' => $headers, 'timeout' => 5, 'cookies' => $cookieJar]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        if ($result['status_code'] == 0) {
            return $this->apiJson(1, 'Cookies值有效，无需扫码登录！', $result);
        } else {
            return $this->apiJson(-1, 'Cookies值已经失效，请重新扫码登录', $result);
        }
    }


    public function homePage()
    {
        $requestUrl = 'https://creator.douyin.com/aweme/v1/creator/homepage/module/';
        $referUrl = "https://creator.douyin.com/";
        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
            'Referer' => $referUrl,
            'Content-Type' => 'application/json'
        ];
        $queryPayload = [
            'aid' => 2906,
            'app_name' => 'aweme_creator_platform',
            'device_platform' => 'web',
            'referer' => 'https://creator.douyin.com/',
            'user_agent' => 'Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/90.0.4430.212+Safari/537.36',
            'cookie_enabled' => 'true',
            'screen_width' => '1536',
            'screen_height' => '864',
            'browser_language' => 'zh-CN',
            'browser_platform' => 'Win32',
            'browser_name' => 'Mozilla',
            'browser_version' => '5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/90.0.4430.212+Safari/537.36',
            'browser_online' => 'true',
            'timezone_name' => 'Asia/Shanghai',
            '_signature' => '_02B4Z6wo00d01p2r8RwAAIDBLVod1OFnSrKdr.WAAMfNMyTYmfaTkAGAaTP6-LSrff82W-To-z7BBN-lNVha6nxzOel.s32F0TlHsuFvqmV-JMIaXdydW6yuwu3Gqixfl4ap-ERjzGA19Qbw87'
        ];
        $str = '';
        foreach ($queryPayload as $k => $v) {
            $str .= "&" . $k . '=' . $v;
        }
        $str = str_replace('/', '%2F', $str);
        $str = str_replace(';', '%3B', $str);
        $url1 = $requestUrl . '?' . substr($str, 1);
        $cookies = [
            'passport_csrf_token_default' => '2e1bfcdc65cb0c2614bd257b838de7fb',
            'passport_csrf_token' => '2e1bfcdc65cb0c2614bd257b838de7fb',
            'MONITOR_WEB_ID' => '1367cc38-d9c9-40b8-8754-fb4c9de0ab0d',
            'ttcid' => '5910c4c5ec3c4558a9104c78e343e39423',
            'csrf_session_id' => '923c504994af4d9c8ff76ffb2a96f034',
            'csrf_token' => 'uUIPewihPVSDuFtMdplMqbqDYISYzFNN',
            's_v_web_id' => 'kp2p7euc_sxJAoFWA_hBQv_4jgq_BbVj_Hsi5QbqGTkOF',
            'n_mh' => 'q_Lw8p8dwgb91irwavm19tur3kRgafNXpsGC-eMrOnY',
            'sso_uid_tt' => 'a398f8215cb68d29330cf2e7cc91af05',
            'sso_uid_tt_ss' => 'a398f8215cb68d29330cf2e7cc91af05',
            'toutiao_sso_user' => '4d672419c2b18f14f62edcbf4a82b270',
            'toutiao_sso_user_ss' => '4d672419c2b18f14f62edcbf4a82b270',
            'odin_tt' => 'ff9d482fcf6ab56ab81afe031c02562f4b7bc9356dc0b5be40d4fd57002ec00575a4c3d6f40bdaceb73b57ce571c8f84',
            'passport_auth_status_ss' => '391fb2b06eb03792a18dba90bbfda164%2C',
            'sid_guard' => 'd6132a6d9395d788a6829bc89df44482%7C1621866151%7C5184000%7CFri%2C+23-Jul-2021+14%3A22%3A31+GMT',
            'uid_tt' => '8d40be7e728fdba2e6fe89478fabb661',
            'uid_tt_ss' => '8d40be7e728fdba2e6fe89478fabb661',
            'sid_tt' => 'd6132a6d9395d788a6829bc89df44482',
            'sessionid' => 'd6132a6d9395d788a6829bc89df44482',
            'sessionid_ss' => 'd6132a6d9395d788a6829bc89df44482',
            'passport_auth_status' => '391fb2b06eb03792a18dba90bbfda164%2C',
            'oc_login_type' => 'LOGIN_PERSON',
            'ttwid' => '1%7CUFQJThWNEfu1-udHxpVabAaHCPl05Z3_BgY9i007bbQ%7C1621866170%7Cfe181cbf99baa9fd0345c0dd0197db3a03d68cb96a2a2e0dd36617c6f3b10e8c',
            'tt_scid' => 'Or07ZSxK2MqQvwnHKLFNEFa4FTz0HmmFA4fYAGQMqhVakeptL0BQ3Gv'
        ];
        $cookieJar = CookieJar::fromArray($cookies, 'creator.douyin.com');
        $jsonPayload = [
            'module_key_list' => ["TOP_MSG", "GENERAL_BANNER", "CREATOR_COLLEGE", "PERSONAL_PROFILE", "PERSONAL_BILLBOARD", "WALLET_INCOME", "WEEK_REPORT", "DATA_OVERVIEW", "MY_ATTENTION"],
            'tpl_id' => '2'
        ];
        try {
            $client = new Client();
            $response = $client->request('post', $url1, [
                'body' => json_encode($jsonPayload), 'headers' => $headers,
                'timeout' => 5, 'cookies' => $cookieJar
            ]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);
        return $this->apiJson(1, 'success', $result);
    }

    //获取视频情况
    public function getUserItem()
    {
        $payload = [
            'access_token' => 'act.a46842a0c2beaa6269db1019b71ec980aWxKNHPj2Qb3cTyp0GntNBX0RBlN',
            'open_id' => '79e91c6a-73a6-4682-a0e8-77dafc1eefec',
            'date_type' => 56
        ];
        $accessTokenUrl = 'https://open.douyin.com/data/external/user/item/';
        try {
            $client = new Client();
            $response = $client->request('GET', $accessTokenUrl, ['query' => $payload, 'timeout' => 5]);
        } catch (\Exception $e) {
            return $this->apiJson(-1, $e->getMessage());
        }
        $result = json_decode($response->getBody()->getContents(), true);

        return $this->apiJson(1, 'success', $result);
    }


    //抖音用户列表
    public function dyUserList()
    {
        $uid = getUid();
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        $dyUser = DyUser::where(['user_id' => $uid, 'is_del' => 0])
            ->field('id,avatar,dy_name,follows,fans,is_auth')
            ->paginate(['list_rows' => $perPage, 'page' => $currentPage]);
        return $this->apiJson(1, 'success', $dyUser);
    }

    //抖音账号详情
    public function dyUserDetail()
    {
        $uid = getUid();
        $id = Request::get('id');
        if (!$id) {
            return $this->apiJson(-1, '缺少id参数');
        }
        $dyUser = DyUser::where(['id' => $id, 'user_id' => $uid, 'is_del' => 0])->field('id,avatar,dy_name,dy_id,follows,likes,fans,works,is_auth')->findOrEmpty();
        if ($dyUser->isEmpty()) {
            return $this->apiJson(-1, '账号不存在');
        }
        return $this->apiJson(1, 'success', $dyUser);
    }

    //删除抖音账号
    public function delDyUser()
    {
        $uid = getUid();
        $id = Request::post('id');
        if (!$id) {
            return $this->apiJson(-1, '缺少id参数');
        }
        $userId = DyUser::where(['id' => $id, 'is_del' => 0])->value('user_id');
        if ($userId != $uid) {
            return $this->apiJson(-1, '你无权限删除');
        }
        DyUser::where(['id' => $id])->update(['is_del' => 1,'is_auth'=>0]);
        return $this->apiJson(1, 'success');
    }

    //抖音地址详情
    public function DyUserAddressDetail()
    {
        $uid = getUid();
        $id = Request::get('id', 0);
        if (!$id) {
            return $this->apiJson(-1, '缺少id参数');
        }
        $address = DyUserAddress::where(['id' => $id, 'user_id' => $uid])
            ->field('id,name,phone,province,city,district,detail_address')
            ->findOrEmpty();
        if ($address->isEmpty()) {
            return $this->apiJson(-1, '该地址不存在或无权限查看');
        }
        return $this->apiJson(1, 'success', $address);
    }

    //抖音地址 创建及更新
    public function DyUserAddress()
    {
        $uid = getUid();
        $id = Request::post('id', 0);
        if ($id) {
            $address = DyUserAddress::where(['id' => $id, 'user_id' => $uid])->findOrEmpty();
            if ($address->isEmpty()) {
                return $this->apiJson(-1, '该地址不存在或无权限修改');
            }
        }
        $addressData = [
            'name' => Request::post('name'),
            'phone' => Request::post('phone'),
            'province' => Request::post('province'),
            'city' => Request::post('city'),
            'district' => Request::post('district'),
            'detail_address' => Request::post('detail_address'),
        ];
        try {
            validate(AddressCheck::class)->check($addressData);
        } catch (ValidateException $e) {
            return $this->apiJson(-1, $e->getMessage());
        }

        $province = Db::name('china_districts')->where(['code' => Request::post('province')])->field('code,name')->find();
        $city = Db::name('china_districts')->where(['code' => Request::post('city')])->field('code,name')->find();
        $district = Db::name('china_districts')->where(['code' => Request::post('district')])->field('code,name')->find();
        if ($id) {
            $addressData['province'] = json_encode($province, JSON_UNESCAPED_UNICODE);
            $addressData['city'] = json_encode($city, JSON_UNESCAPED_UNICODE);
            $addressData['district'] = json_encode($district, JSON_UNESCAPED_UNICODE);
            DyUserAddress::where(['id' => $id])->update($addressData);
        } else {
            $addressData['user_id'] = $uid;
            $addressData['province'] = $province;
            $addressData['city'] = $city;
            $addressData['district'] = $district;
            DyUserAddress::create($addressData);
        }
        return $this->apiJson(1, 'success');
    }

    //抖音地址列表
    public function DyUserAddressList()
    {
        $currentPage = Request::get('current_page') ? Request::get('current_page') : 1;
        $perPage = $this->getPerPage();
        $uid = getUid();
        $list = DyUserAddress::where(['user_id' => $uid])
            ->order('create_time','desc')
            ->field('id,name,phone,province,city,district,detail_address')
            ->paginate(['list_rows' => $perPage, 'page' => $currentPage]);
        return $this->apiJson(1, 'success', $list);
    }

    //删除
    public function DyUserAddressDel()
    {
        $uid = getUid();
        $id = Request::post('id', 0);
        if (!$id) {
            return $this->apiJson(-1, '缺少id参数');
        }
        $address = DyUserAddress::where(['id' => $id, 'user_id' => $uid])->findOrEmpty();
        if ($address->isEmpty()) {
            return $this->apiJson(-1, '该地址不存在或无权限删除');
        }
        DyUserAddress::where(['id' => $id, 'user_id' => $uid])->delete();
        return $this->apiJson(1, 'success');
    }
}
